package com.lenovo.nova.util.io;

import java.io.*;

public class StreamUtil {
	
	public static StreamUtil instance = new StreamUtil();
	
	public static StreamUtil getInstance(){
		return instance;
	}
	
	  public  static byte[] streamToBytes(InputStream is) {
          ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
          byte[] buffer = new byte[1024];
          int len;
          try {
              while ((len = is.read(buffer)) >= 0) {
                  os.write(buffer, 0, len);
              }
          } catch (java.io.IOException e) {
          }
          return os.toByteArray();
      }
	
	public static String streamToString(InputStream inputStream , OnReadStreamHelper helper) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null ) {
				if(helper != null){
					helper.onReaderLine(line);
					if(helper.isTerminal()){
						break;
					}
				}
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	
	public static void streamToFile(InputStream in,File file){
		FileOutputStream fileOut = null; 
		try {
			fileOut = new FileOutputStream(file);
			byte[] buffer = new byte[1024 * 10];
			int lenght = 0;
			while((lenght = in.read(buffer , 0, buffer.length)) != -1){
				fileOut.write(buffer, 0, lenght);
			}
			fileOut.flush();
			fileOut.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(fileOut != null){
					fileOut.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

    public static String fileToSting(File file) {
        try {
            InputStream in = new FileInputStream(file);
            return streamToString(in,null);
        } catch (Exception e) {
            return e.toString();
        }
    }


    public interface OnReadStreamHelper{
		boolean isTerminal();
		void onReaderLine(String line);
	}

}
